package com.zhfi.dataapply.schedule.reader;

import com.alibaba.fastjson.JSON;
import com.zhfi.dataapply.entity.TzResponse;
import com.zhfi.dataapply.entity.job.JobRangeDateObj;
import com.zhfi.dataapply.service.ForwardService;
import com.zhfi.dataapply.service.common.JobRangeDateService;
import org.springframework.batch.item.ItemReader;
import org.springframework.util.CollectionUtils;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 根据起始结束日期和页码查询数据
 */
public abstract class AbstractRangeDateReader<T> implements ItemReader<T>{

    private String startDate;
    private String endDate;
    private int pageIndex;
    private List<T> dataList;
    private int dataSiteNum;
    private Class<T> clazz;
    private ForwardService forwardService;
    private JobRangeDateService jobRangeDateService;

    public AbstractRangeDateReader(Class<T> clazz, ForwardService forwardService,
                                   JobRangeDateService jobRangeDateService) {
        this.clazz = clazz;
        this.forwardService = forwardService;
        this.jobRangeDateService = jobRangeDateService;
    }

    @Override
    public T read() {
        //如果已读完所有页码，则返回null
        if (CollectionUtils.isEmpty(dataList)) {
            return null;
        }
        if (dataSiteNum >= dataList.size()) {
            pageIndex ++;
            dataSiteNum = 0;
            readPage();
            //如读完下一页信息后没有数据，则返回null
            if (CollectionUtils.isEmpty(dataList)) {
                return null;
            }
        }
        return dataList.get(dataSiteNum ++);
    }

    /**
     * 读取当页数据
     */
    private void readPage() {
        TzResponse tzResponse = forwardService.requestForwarder(getUrl(), getParamsMap());
        if (null != tzResponse && !CollectionUtils.isEmpty(tzResponse.getData())) {
            dataList = JSON.parseArray(JSON.toJSONString(tzResponse.getData()), clazz);
        } else {
            dataList = Collections.emptyList();
        }
    }

    protected Map<String, Object> getParamsMap() {
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("startDate", startDate);
        paramsMap.put("endDate", endDate);
        paramsMap.put("pageIndex", pageIndex);
        return paramsMap;
    }

    /**
     * 设置任务读取起始日期和结束日期
     */
    private void setStartDateAndEndDate() {
        JobRangeDateObj jobRangeDateObj = jobRangeDateService.getRangeDateParam(getJobId());
        this.startDate = jobRangeDateObj.getStartDate();
        this.endDate = jobRangeDateObj.getEndDate();
    }

    protected abstract String getJobId();

    public void reset() {
        this.pageIndex = 1;
        this.dataSiteNum = 0;
        dataList = Collections.emptyList();
        setStartDateAndEndDate();
        resetUrl();
        readPage();
    }

    public abstract String getUrl();
    protected abstract void resetUrl();
}
